package controllers

import (
	"fmt"
	"goblog/app/models/article"
	"goblog/app/models/category"
	"goblog/app/requests"
	"goblog/pkg/flash"
	"goblog/pkg/route"
	"goblog/pkg/view"
	"net/http"
)

type CategoriesController struct {
	BaseController
}

// Create 新建表单
func (cc *CategoriesController) Create(w http.ResponseWriter, r *http.Request) {
	view.Render(w, view.D{}, "categories.create")
}

// Store 存储逻辑
func (cc *CategoriesController) Store(w http.ResponseWriter, r *http.Request) {

	_category := category.Category{
		Name: r.PostFormValue("name"),
	}
	errs := requests.ValidateCategoryForm(_category)

	if len(errs) == 0 {
		_ = _category.Create()
		if _category.Id > 0 {
			flash.Success("分类创建成功")
			indexUrl := route.Name2URL("home")
			http.Redirect(w, r, indexUrl, http.StatusFound)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			_, _ = fmt.Fprint(w, "创建分类失败，请联系管理员")
		}
	} else {
		view.Render(w, view.D{
			"Category": _category,
			"Errors":   errs,
		}, "categories.create")
	}
}

// Show 展示分类
func (cc *CategoriesController) Show(w http.ResponseWriter, r *http.Request) {

	id := route.GetRouteVariable("id", r)

	_category, err := category.Get(id)

	// 获取结果集
	articles, pagerData, err := article.GetByCategoryID(_category.GetStringID(), r, 2)

	if err != nil {
		cc.ResponseForSQLError(w, err)
	} else {

		view.Render(w, view.D{
			"Articles":  articles,
			"PagerData": pagerData,
		}, "articles.index", "articles._article_meta")
	}
}
